package registeyconfig

import (
	"io/ioutil"
	"os"

	"github.com/micro/go-micro/v2/logger"
	"github.com/micro/go-micro/v2/registry"
	"gopkg.in/yaml.v2"
)

type RegistryConfig struct {
	Params   map[string]string            `yaml:"params"`   //配置参数
	Services map[string]*registry.Service `yaml:"services"` //服务列表
}

func NewRegistryConfig() *RegistryConfig {
	regCfg := new(RegistryConfig)
	regCfg.Params = make(map[string]string)
	regCfg.Services = make(map[string]*registry.Service)
	return regCfg
}

func (rc *RegistryConfig) GetService(serviceName string) (*registry.Service, bool) {
	s, bExist := rc.Services[serviceName]
	return s, bExist
}

func (rc *RegistryConfig) AddService(serviceName string, s *registry.Service) error {
	rc.Services[serviceName] = s
	return nil
}

func (rc *RegistryConfig) DelService(serviceName string, s *registry.Service) error {
	delete(rc.Services, serviceName)
	return nil
}

func (rc *RegistryConfig) GetParam(key string) (string, bool) {
	s, bExist := rc.Params[key]
	return s, bExist
}

func (rc *RegistryConfig) SetParam(key string, value string) error {
	rc.Params[key] = value
	return nil
}

func (rc *RegistryConfig) Load(fileName string) error {

	data, err := ioutil.ReadFile(fileName)
	if nil != err {
		logger.Error("load RegistryConfig error", err)
	} else {
		err = rc.LoadData(data)
	}

	return err
}

func (rc *RegistryConfig) LoadData(data []byte) error {

	err := yaml.Unmarshal(data, rc)

	for k, r := range rc.Services {
		logger.Infof("RegistryConfig [%s]: [%v]", k, r)
	}

	return err
}

func (rc *RegistryConfig) Write(fileName string) error {

	yfile, _ := os.Create(fileName)

	defer yfile.Close()

	yencoder := yaml.NewEncoder(yfile)

	defer yencoder.Close()

	return yencoder.Encode(rc)

}
